package com.ist.word.audio;

import javax.sound.*;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;

import java.io.*;
import java.net.URLDecoder;

public class AudioPlayer {

	private Clip audioClip;

	public static void main(String args[]) throws Exception {
		AudioPlayer sound = new AudioPlayer("/audios/SoundTest.wav");
	}

	public AudioPlayer() {
	}

	// filename"/audio/SoundTest.wav"
	public AudioPlayer(String filename) {
			AudioInputStream inputStream = null;
			try {
				/*
				filename = URLDecoder.decode(
						this.getClass().getResource(filename).getPath(), "UTF-8");
				inputStream = AudioSystem.getAudioInputStream(new File(
						filename));*/
				String proFilePath = System.getProperty("user.dir") + filename;
				filename = URLDecoder.decode(proFilePath, "UTF-8");
				//InputStream is=this.getClass().getResourceAsStream(filename);   
		        inputStream=AudioSystem.getAudioInputStream(new File(filename));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			AudioFormat format = inputStream.getFormat();


			// create a clip to play to

			try {
				DataLine.Info info = new DataLine.Info(Clip.class, format);
				audioClip = (Clip) AudioSystem.getLine(info);
				audioClip.open(inputStream);

			} catch (LineUnavailableException ex) {
				ex.printStackTrace();
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		

	}

	public void play() {
		audioClip.start();
	}
	public void loop() {
		audioClip.loop(20);
	}
	public boolean audioStatus() {
		return audioClip.isActive();
	}

	public void pause() {
		if (audioClip.isActive()) {
			audioClip.stop();
		}
	}

	 public void reset() {
		 if (audioClip.isActive()) {
				audioClip.stop();
				audioClip.setMicrosecondPosition(0);
		 }	 
	 }
}